package cn.tedu.smartos.family_user.service.impl;

import cn.tedu.smartos.base.exception.ServiceException;
import cn.tedu.smartos.base.response.StatusCode;
import cn.tedu.smartos.family_user.mapper.ElectronicFenceMapper;
import cn.tedu.smartos.family_user.pojo.dto.FenceParam;
import cn.tedu.smartos.family_user.pojo.entity.ElectronicFence;
import cn.tedu.smartos.family_user.service.ElderlyBindService;
import cn.tedu.smartos.family_user.service.FenceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class FenceServiceImpl implements FenceService {

    @Autowired
    private ElectronicFenceMapper fenceMapper;

    @Autowired
    private ElderlyBindService elderlyBindService;

    @Transactional
    @Override
    public void createFence(FenceParam param) {
        // 校验家属与老人的绑定关系
        if (!elderlyBindService.isValidRelation(
                param.getFamilyUserId(),
                param.getElderlyUserId())) {
            throw new ServiceException(StatusCode.INVALID_REQUEST, "家属与老人无绑定关系");
        }

        ElectronicFence fence = new ElectronicFence();
        BeanUtils.copyProperties(param, fence);
        fence.setCreateTime(new Date());
        fence.setUpdateTime(new Date());
        fence.setLastStatus(0); // 初始状态：围栏内

        fenceMapper.insertFence(fence);
    }

    @Transactional
    @Override
    public void updateFence(FenceParam param) {
        // 获取现有围栏
        ElectronicFence existing = fenceMapper.selectFenceById(param.getFenceId());
        if (existing == null) {
            throw new ServiceException(StatusCode.INVALID_REQUEST, "围栏不存在");
        }

        // 校验操作权限（只能修改自己创建的围栏）
        if (!existing.getFamilyUserId().equals(param.getFamilyUserId())) {
            throw new ServiceException(StatusCode.INVALID_REQUEST, "只能修改自己创建的围栏");
        }

        // 更新围栏信息
        ElectronicFence fence = new ElectronicFence();
        BeanUtils.copyProperties(param, fence);
        fence.setUpdateTime(new Date());
        // 保留原有的家属用户ID（防止前端篡改）
        fence.setFamilyUserId(existing.getFamilyUserId());

        fenceMapper.updateFence(fence);
    }

    @Transactional
    @Override
    public void deleteFence(Long fenceId) {
//        public void deleteFence(Long fenceId, Long currentUserId) {
        // 获取现有围栏
        ElectronicFence fence = fenceMapper.selectFenceById(fenceId);
        if (fence == null) {
            throw new ServiceException(StatusCode.INVALID_REQUEST, "围栏不存在");
        }
// 添加详细日志
//        log.info("删除围栏验证 - 围栏ID: {}, 当前用户ID: {}, 围栏创建者ID: {}",
//                fenceId, currentUserId, fence.getFamilyUserId());
//        // 校验权限：当前用户必须是围栏创建者
//        if (!fence.getFamilyUserId().equals(currentUserId)) {
//            throw new ServiceException(StatusCode.INVALID_REQUEST,
//                    "无权操作该围栏。当前用户ID: " + currentUserId +
//                            ", 围栏创建者ID: " + fence.getFamilyUserId());
//        }
        fenceMapper.deleteFence(fenceId);
    }

    @Override
    public List<ElectronicFence> getFencesByFamily(Long familyUserId) {
        return fenceMapper.selectFencesByFamily(familyUserId);
    }

    @Override
    public List<ElectronicFence> getFencesByElderly(Long elderlyUserId) {
        return fenceMapper.selectFencesByElderly(elderlyUserId);
    }

    @Override
    public ElectronicFence getFenceById(Long fenceId) {
        ElectronicFence fence = fenceMapper.selectFenceById(fenceId);
        if (fence == null) {
            throw new ServiceException(StatusCode.INVALID_REQUEST, "围栏不存在");
        }
        return fence;
    }
}